<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    protected $table = 'ims_yz_address';
    
    protected $fillable = [
        'areaname',
        'parentid',
        'level'
    ];

    protected $casts = [
        'id' => 'integer',
        'parentid' => 'integer',
        'level' => 'integer'
    ];

    /**
     * 获取省份列表
     */
    public static function getProvinces()
    {
        return self::where('level', 1)
            ->orderBy('id')
            ->get(['id', 'areaname']);
    }

    /**
     * 根据省份ID获取城市列表
     */
    public static function getCitiesByProvince($provinceId)
    {
        return self::where('level', 2)
            ->where('parentid', $provinceId)
            ->orderBy('id')
            ->get(['id', 'areaname']);
    }

    /**
     * 根据城市ID获取区县列表
     */
    public static function getDistrictsByCity($cityId)
    {
        return self::where('level', 3)
            ->where('parentid', $cityId)
            ->orderBy('id')
            ->get(['id', 'areaname']);
    }

    /**
     * 获取完整地址
     */
    public function getFullAddressAttribute()
    {
        $address = $this->areaname;
        
        if ($this->level == 3 && $this->parentid) {
            $city = self::find($this->parentid);
            if ($city && $city->parentid) {
                $province = self::find($city->parentid);
                if ($province) {
                    $address = $province->areaname . $city->areaname . $address;
                }
            }
        }
        
        return $address;
    }
}